﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using Common.Model;
using Dapper.Contrib.Extensions;
using Newtonsoft.Json.Linq;
using pinduoduo.Model;
using pinduoduo.Util;
using System.Linq;
using Sunny.UI;
using Tk.Soc.Share.Common.Helpers;

namespace pinduoduo.From
{
    public partial class BrowserNewFrom : UIForm
    {

        private ChromiumWebBrowser AccountChromeBrowser;

        private RequestContext AccountContext;

        public Action UpdateGoodInfoAction;
        public Action<string> SetGoodIdAction;

        private string url;

        PddGoodSource pddGoodSource;

        public BrowserNewFrom(string url,PddToken pddToken=null, PddGoodSource pddGoodSource= PddGoodSource.ZhiBo)
        {
            this.url = url;
            this.pddGoodSource = pddGoodSource;
            InitializeComponent();
            InitializeAccountChromium();
            if (pddToken != null) 
            {
                SetToken(pddToken);
            }
        }


        async void SetToken(PddToken pddToken) 
        {
            await AccountContext.GetCookieManager(null).DeleteCookiesAsync(pddurl, "PDDAccessToken");
            await AccountContext.GetCookieManager(null).DeleteCookiesAsync(pddurl, "pdd_user_id");

            var PDDAccessToken = new CefSharp.Cookie
            {
                Path = "/",
                Domain = "yangkeduo.com",
                Creation = DateTime.Today,
                Expires = DateTime.Today.AddDays(30),
                Name = "PDDAccessToken",
                Value = pddToken.PDDAccessToken
            };
            var pdd_user_id = new CefSharp.Cookie
            {
                Path = "/",
                Domain = "yangkeduo.com",
                Creation = DateTime.Today,
                Expires = DateTime.Today.AddDays(30),
                Name = "pdd_user_id",
                Value = pddToken.pdd_user_id
            };
            await AccountContext.GetCookieManager(null).SetCookieAsync(pddurl, pdd_user_id);
            await AccountContext.GetCookieManager(null).SetCookieAsync(pddurl, PDDAccessToken);
        }

        private void AutoPayFrom_Load(object sender, EventArgs e)
        {

        }

        //初始化浏览器并启动
        public void InitializeAccountChromium()
        {

            AccountContext = new RequestContext(new RequestContextSettings()
            {
                CachePath = AppDomain.CurrentDomain.BaseDirectory + "caches\\global1\\",
                PersistSessionCookies = true,
                PersistUserPreferences = true
            });

            AccountChromeBrowser = new ChromiumWebBrowser(this.url, AccountContext);
            BrowserSettings browserSettings = new BrowserSettings();
            browserSettings.ApplicationCache = CefState.Enabled;
         
            AccountChromeBrowser.BrowserSettings = browserSettings;

#if DEBUG
            AccountChromeBrowser.KeyboardHandler = new CEFKeyBoardHander();
#endif
            this.panel1.Controls.Add(AccountChromeBrowser);


            AccountChromeBrowser.IsBrowserInitializedChanged += OnIsBrowserInitializedChanged;

            AccountChromeBrowser.Dock = DockStyle.Fill;
        }

        private void OnIsBrowserInitializedChanged(object sender, EventArgs args)
        {
            SetCookie(CefUtils.GetAccountContext());
            AccountChromeBrowser.Load(this.url);
        }

        private string pddurl = "http://yangkeduo.com/";

        public async void SetCookie(RequestContext AccountContext)
        {
            List<CefSharp.Cookie> cookies = await AccountContext.GetCookieManager(null).VisitUrlCookiesAsync(pddurl, true);

            foreach (var item in cookies)
            {
                await AccountChromeBrowser.GetCookieManager().SetCookieAsync(pddurl, item);
            }
        }

        public void GetDuoDuoGoodInfo(JObject jo)
        {
            PddGood pddGood = new PddGood();
            
            string activityID = jo["goods"]["activity"]?["activityID"]?.ToString();
            string mallId = jo["goods"]["mallID"].ToString();

            string _oc_mkt_domain = jo["queries"]["_oc_mkt_domain"].ToString();
            string _oc_mkt_tr_sc = jo["queries"]["_oc_mkt_tr_sc"].ToString();
            string _oc_mkt_tr_token = jo["queries"]["_oc_mkt_tr_token"].ToString();
            string refer_page_id = jo["queries"]["refer_page_id"].ToString();
            string refer_page_name = jo["queries"]["refer_page_name"].ToString();
            string refer_page_sn = jo["queries"]["refer_page_sn"].ToString();
            string goods_id = jo["queries"]["goods_id"].ToString();
            string _oc_pid = jo["queries"]["_oc_pid"].ToString();
            var cpsSign = jo["queries"]["_oc_cps_sign"].ToString();

            try
            {
            
                var promotionDetails = jo["lisbonInfo"]["promotionPriceInfo"]?["promotionDetails"]?.ToString();
               
                if (!string.IsNullOrWhiteSpace(promotionDetails))
                {
                    var promotionDetailsJo = JObject.Parse(promotionDetails);
                    string merchantBatchSn = promotionDetailsJo["merchantBatchSn"].ToString();
                    string merchantCouponId = promotionDetailsJo["merchantCouponId"].ToString();
                    pddGood.merchantBatchSn = merchantBatchSn;
                    pddGood.merchantCouponId = merchantCouponId;
             
                }

                var coupon_list = jo["lisbonInfo"]["newMallCoupons"]?["couponList"]?.ToArray();
                var mallCoupons = jo["lisbonInfo"]["mallCoupons"].ToArray();
                if (coupon_list != null)
                {
                    pddGood.coupon_list = JsonHelper.SerializeObject(coupon_list);
                }
            }
            catch (Exception e)
            {
                
            }
      

            pddGood.good_id = goods_id;
            pddGood.atvid = activityID;
            pddGood.duo_duo_pid = _oc_pid;
            pddGood.cps_sign = cpsSign;
            pddGood.mall_id = mallId;
            pddGood.mkt_domain = _oc_mkt_domain;
            pddGood.mkt_tr_sc = _oc_mkt_tr_sc;
            pddGood.mkt_tr_token = _oc_mkt_tr_token;

            pddGood.refer_page_id = refer_page_id;
            pddGood.refer_page_name = refer_page_name;
            pddGood.refer_page_sn = refer_page_sn;
            pddGood.type = (int)PddGoodSource.DuoDuo;
            try
            {
                var groupTypes = jo["goods"]["groupTypes"];
                if (groupTypes.Count() > 0)
                {
                    pddGood.gID2 = groupTypes[0]["groupID"].ToString();
                }
                if (groupTypes.Count() > 1)
                {
                    pddGood.gID1 = groupTypes[1]["groupID"].ToString();
                }

                var skus = jo["goods"]["skus"];
                string skuJson = JsonHelper.SerializeObject(skus);
                pddGood.sku = skuJson;
            }
            catch
            {
            }

            PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(goods_id);
            if (pdd == null)
            {
                long reslut = DataBaseHelper.SqLiteDBCon.Insert(pddGood);
            }
            else
            {
                pddGood.SourceKeywords = pdd.SourceKeywords;

                DataBaseHelper.SqLiteDBCon.Update<PddGood>(pddGood);
            }
            this.BeginInvoke(new Action(() =>
            {
                SetGoodIdAction?.Invoke(goods_id);
                UpdateGoodInfoAction?.Invoke();
                MessageBox.Show("获取数据成功");
            }));
        }
             
         






            //var goods_id = jo["queries"]["goods_id"].ToString();
            //var skus = jo["goods"]["skus"];
            //string skuJson = JsonHelper.SerializeObject(skus);
            //pddGood.sku = skuJson;
            //pddGood.good_id = goods_id;

            //var groupTypes = jo["goods"]["groupTypes"];
            //if (groupTypes.Count() > 0)
            //{
            //    pddGood.gID2 = groupTypes[0]["groupID"].ToString();
            //}
            //if (groupTypes.Count() > 1)
            //{
            //    pddGood.gID1 = groupTypes[1]["groupID"].ToString();
            //}
            //pddGood.type = (int)PddGoodSource.PuTongHtml;
            //PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(goods_id);
            //if (pdd == null)
            //{
            //    long reslut = DataBaseHelper.SqLiteDBCon.Insert(pddGood);
            //}
            //else
            //{
            //    pddGood.SourceKeywords = pdd.SourceKeywords;

            //    DataBaseHelper.SqLiteDBCon.Update<PddGood>(pddGood);
            //}
            //this.BeginInvoke(new Action(() =>
            //{
            //    SetGoodIdAction?.Invoke(goods_id);
            //    UpdateGoodInfoAction?.Invoke();
            //    //MessageBox.Show("获取数据成功");
            //    ShowSuccessNotifier("获取数据成功");
            //}));
        //}

        private async void GetNetGoodButton_Click(object sender, EventArgs e)
        {
            try
            {
                string script = @"(function() { return  window.rawData.store.initDataObj;})()";
                //if (this.pddGoodSource == PddGoodSource.ZhiBo) {

                await AccountChromeBrowser.EvaluateScriptAsync(script).ContinueWith(x =>
                {
                    var response = x.Result;

                    if (response.Success && response.Result != null)
                    {
                        var jo = JObject.FromObject(response.Result);
                        if (this.pddGoodSource == PddGoodSource.ZhiBo)
                        {
                            try
                            {
                                var goods_id = jo["queries"]["goods_id"].ToString();


                                var _oc_n_mkt_tr_token = jo["queries"]["_oc_n_mkt_tr_token"].ToString();
                                var _oc_n_mkt_domain = jo["queries"]["_oc_n_mkt_domain"].ToString();
                                var _oc_n_mkt_tr_sc = jo["queries"]["_oc_n_mkt_tr_sc"].ToString();
                                var _oc_live_show_id = jo["queries"]["_oc_live_show_id"].ToString();
                                var refer_page_name = jo["queries"]["refer_page_name"]?.ToString();
                                var refer_page_id = jo["queries"]["refer_page_id"]?.ToString();
                                var refer_page_sn = jo["queries"]["refer_page_sn"]?.ToString();

                                PddGood pddGood = new PddGood();
                                pddGood.good_id = goods_id;
                                pddGood.type = (int)PddGoodSource.ZhiBo;
                                pddGood.live_show_id = _oc_live_show_id;
                                pddGood.mkt_domain = _oc_n_mkt_domain;
                                pddGood.mkt_tr_sc = _oc_n_mkt_tr_sc;
                                pddGood.mkt_tr_token = _oc_n_mkt_tr_token;

                                pddGood.refer_page_id = refer_page_id;
                                pddGood.refer_page_name = refer_page_name;
                                pddGood.refer_page_sn = refer_page_sn;

                                var groupTypes = jo["goods"]["groupTypes"];
                                if (groupTypes.Count() > 0)
                                {
                                    pddGood.gID2 = groupTypes[0]["groupID"].ToString();
                                }
                                if (groupTypes.Count() > 1)
                                {
                                    pddGood.gID1 = groupTypes[1]["groupID"].ToString();
                                }

                                var skus = jo["goods"]["skus"];
                                string skuJson = JsonHelper.SerializeObject(skus);
                                pddGood.sku = skuJson;


                                PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(goods_id);
                                if (pdd == null)
                                {
                                    long reslut = DataBaseHelper.SqLiteDBCon.Insert(pddGood);
                                }
                                else
                                {
                                    pddGood.SourceKeywords = pdd.SourceKeywords;

                                    DataBaseHelper.SqLiteDBCon.Update<PddGood>(pddGood);
                                }
                                this.BeginInvoke(new Action(() =>
                                {
                                    SetGoodIdAction?.Invoke(goods_id);
                                    UpdateGoodInfoAction?.Invoke();
                                    //MessageBox.Show("获取数据成功");
                                    ShowSuccessNotifier("获取数据成功");
                                }));

                            }
                            catch
                            {
                                ShowErrorNotifier("获取数据失败");
                            }
                        }
                        else if (this.pddGoodSource == PddGoodSource.PuTong)
                        {
                            PddGood pddGood = new PddGood();

                            var goods_id = jo["queries"]["goods_id"].ToString();
                            var skus = jo["goods"]["skus"];
                            string skuJson = JsonHelper.SerializeObject(skus);
                            pddGood.sku = skuJson;
                            pddGood.good_id = goods_id;

                            var groupTypes = jo["goods"]["groupTypes"];
                            if (groupTypes.Count() > 0)
                            {
                                pddGood.gID2 = groupTypes[0]["groupID"].ToString();
                            }
                            if (groupTypes.Count() > 1)
                            {
                                pddGood.gID1 = groupTypes[1]["groupID"].ToString();
                            }
                            pddGood.type = (int)PddGoodSource.PuTongHtml;
                            PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(goods_id);
                            if (pdd == null)
                            {
                                long reslut = DataBaseHelper.SqLiteDBCon.Insert(pddGood);
                            }
                            else
                            {
                                pddGood.SourceKeywords = pdd.SourceKeywords;

                                DataBaseHelper.SqLiteDBCon.Update<PddGood>(pddGood);
                            }
                            this.BeginInvoke(new Action(() =>
                            {
                                SetGoodIdAction?.Invoke(goods_id);
                                UpdateGoodInfoAction?.Invoke();
                                //MessageBox.Show("获取数据成功");
                                ShowSuccessNotifier("获取数据成功");
                            }));
                            //foreach (dynamic item in skuObj)
                            //{
                            //    double skuId = item.skuId;
                            //    string normalPrice = item.normalPrice;
                            //    string groupPrice = item.groupPrice;
                            //    dynamic specs = item.specs;
                            //    double goodsId = item.goodsId;

                            //    string spec_value = "";
                            //    foreach (dynamic spec in specs)
                            //    {
                            //        spec_value = spec.spec_value;
                            //    }
                            //    string text = "拼单:" + groupPrice + " 元" + "单买:" + normalPrice + "元 " + spec_value;


                            //}


                        }
                        else if (this.pddGoodSource == PddGoodSource.DuoDuo)
                        {
                            GetDuoDuoGoodInfo(jo);
                        }
                    }
                    return;
                });
                //}
            }
            catch (Exception e1)
            {
                ShowErrorNotifier("抓取失败");
                LogHelper.Logger.Error("抓取失败", e1);
            }
      

        }
    }
}
